package com.example.c4;

import lombok.extern.slf4j.Slf4j;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.Buffer;
import java.nio.ByteBuffer;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.util.ArrayList;
import java.util.List;

/**
 * @author Jonathan
 * 2021/5/28 21:17
 */

@Slf4j
public class Server {
    // static Logger log = LoggerFactory.getLogger(Object.class);

    public static void main(String[] args) throws IOException {
        try {
            ByteBuffer buffer = ByteBuffer.allocate(16);
            ServerSocketChannel serverSocketChannel = ServerSocketChannel.open();
            serverSocketChannel.configureBlocking(false);//  设置为非阻塞模式
            serverSocketChannel.bind(new InetSocketAddress(8080));
            List<SocketChannel> list = new ArrayList<>();
            while (true) {
                SocketChannel socketChannel = serverSocketChannel.accept();// 阻塞的
                // 设置为非阻塞的 下面的read方法就是非阻塞的
                if (socketChannel != null) {
                    System.out.printf("connected.sc:%s\n", socketChannel);
                    socketChannel.configureBlocking(false);
                    list.add(socketChannel);
                }
                for (SocketChannel channel : list) {
                    System.out.printf("before read:%s\n", channel);
                    int read = channel.read(buffer);// 阻塞的方法--->非阻塞的
                    if (read > 0) {
                        System.out.printf("after read:%s\n", channel);
                        Buffer flip = buffer.flip();
                        System.out.println(buffer);
                        buffer.clear();
                    }
                }
            }

        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
